package com.scott.base.utils;


import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 黄后林
 * @version 1.0
 * @note
 * @date 2021-11-27 15:38:37
 */
public class AESUtil {
    // Java利用  AES/ECB/PKCS5Padding 算法加解密
    private static final String AES_KEY_ALGORITHM  = "AES/ECB/PKCS5Padding";

    // 随机生成的私钥
    public static final String KEY="59287624-9c5f-4ce2-897e-36d8f89d";

    /**
     * 加密
     * @param data 需要加密的数据
     * @param secret 加密用的私钥
     * @return String
     */
    public static String encrypt(String data, String secret) throws Exception {
        if (data == null || secret == null) {
            return null;
        }
        String charsetName = "utf-8";
        Cipher cipher = Cipher.getInstance(AES_KEY_ALGORITHM); //算法/模式/补码方式
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret.getBytes(charsetName), "AES"));
        byte[] encrypted = cipher.doFinal(data.getBytes(charsetName));
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * 解密
     * @param data
     * @param secret
     * @return String
     * @throws Exception
     */
    public static String decrypt(String data, String secret) throws Exception {
        if (data == null || secret == null) {
            return null;
        }
        String charsetName = "utf-8";
        Cipher cipher = Cipher.getInstance(AES_KEY_ALGORITHM); //算法/模式/补码方式
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret.getBytes(charsetName), "AES"));
        byte[] encrypted = Base64.decodeBase64(data);
        return new String(cipher.doFinal(encrypted), charsetName);
    }
}
